package com.huawei.hiimagesegmentation.ui;

import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.huawei.hiimagesegmentation.R;
import com.huawei.hiimagesegmentation.bean.ModelTrackingResult;
import com.huawei.hiimagesegmentation.camera.CameraPreview;
import com.huawei.hiimagesegmentation.help.ImageDegreeHelper;
import com.huawei.hiimagesegmentation.help.ImageUtils;
import com.huawei.hiimagesegmentation.help.TrackingMobile;

import java.io.File;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements CameraPreview.ICameraDataCallBack {

    private static final String TAG = "MainActivity";

    public static final String ENTER_TYPE = "enter_type";
    public static final int TYPE_PHOTO = 1;
    public static final int TYPE_CAMERA = 2;

    private int getTypeEnter;

    private FloatingActionButton cameraBtn;
    private RelativeLayout findLayout;
    private CameraPreview cameraPreview;

    private ImageView originalImg, resultImg, maskImg;
    private TrackingMobile trackingMobile;

    private LinearLayout contentLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getTypeEnter = getIntent().getIntExtra(ENTER_TYPE, 0);
        init();
    }

    private void init() {
        findLayout = findViewById(R.id.view_finder);
        cameraBtn = findViewById(R.id.capture_button);
        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePicture();
            }
        });

        originalImg = findViewById(R.id.original_imageview);
        resultImg = findViewById(R.id.result_imageview);
        maskImg = findViewById(R.id.mask_imageview);

        contentLayout = findViewById(R.id.content_layout);

        if (TYPE_PHOTO == getTypeEnter) {
            cameraBtn.setVisibility(View.INVISIBLE);
            fromPhotoShowIamge();
        } else {
            cameraBtn.setVisibility(View.VISIBLE);
            addCameraPreView();
        }

        trackingMobile = new TrackingMobile(this, false);
    }

    private void takePicture() {
        if (cameraPreview != null) {
            cameraPreview.takePicture();
        }
    }

    private void fromPhotoShowIamge() {
        Uri uri = getIntent().getData();
        String imgPath = ImageDegreeHelper.getPath(this, uri);
        int degree = ImageDegreeHelper.readPictureDegree(imgPath);
        Bitmap originBitmap = BitmapFactory.decodeFile(imgPath);
        if (originBitmap != null) {
            Bitmap bitmap = ImageDegreeHelper.rotaingImageView(degree, originBitmap.copy(Bitmap.Config.ARGB_8888, true));
            if (bitmap != null) {
                ImageView imageView = new ImageView(this);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);//居中显示。
                imageView.setImageBitmap(bitmap);
                findLayout.addView(imageView, lp);
            }
        }
    }

    private void addCameraPreView() {
        cameraPreview = new CameraPreview(this);
        cameraPreview.addCameraDataCallBack(this);

        cameraPreview.setForegroundGravity(Gravity.CENTER);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);//居中显示。
        findLayout.addView(cameraPreview, lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TYPE_CAMERA == getTypeEnter && cameraPreview != null) {
            cameraPreview.onResume(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (TYPE_CAMERA == getTypeEnter && cameraPreview != null) {
            cameraPreview.onPause();
        }
    }


    @Override
    public void takeCameraDataCallBack(final File file) {
        if (file != null) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = ImageUtils.decodeBitmap(file);
                    ModelTrackingResult modelTrackingResult = trackingMobile.execute(bitmap);

                    setImageView(originalImg, modelTrackingResult.getBitmapOriginal());
                    setImageView(resultImg, modelTrackingResult.getBitmapResult());
                    setImageView(maskImg, modelTrackingResult.getBitmapMaskOnly());

                    fillContent(modelTrackingResult.getExecutionLog(),modelTrackingResult.getItemsFound());
                }
            });
        }
    }

    private void setImageView(ImageView imageView, Bitmap image) {
        Glide.with(getApplicationContext())
                .load(image)
                .override(512, 512)
                .fitCenter()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(imageView);
    }

    private void fillContent(String executionLog, Set<Integer> itemsFound) {
        contentLayout.removeAllViews();

        TextView textView = new TextView(this);
        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setText(executionLog);
        contentLayout.addView(textView);

        for (int i = 0; i < TrackingMobile.NUM_CLASSES; i++) {
            if (itemsFound.contains(i)) {
                TextView tv = new TextView(this);
                tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                tv.setText(TrackingMobile.labelsArrays[i]);
                tv.setBackgroundColor((TrackingMobile.segmentColors[i]));

                contentLayout.addView(tv);
            }
        }
    }

}